import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-02-13
 * Time: 14:57
 */
public class Test {

    //括号的匹配问题
    public static boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else {
                if(stack.isEmpty()){
                    return false;
                }
                char ch2 = stack.peek();
                if(ch2 == '(' && ch == ')' || ch2 == '[' && ch == ']'
                        || ch2 == '{' && ch == '}'){

                    stack.pop();

                } else {
                    return false;
                }

            }
        }

        if(!stack.isEmpty()){
            return false;
        }
        return true;

    }

    //逆波兰表达式求值
    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(int  i = 0; i < tokens.length; i++){
            String str = tokens[i];
            if (isOperation(str)){
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch(str){
                    case "+":
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                }
            } else {
                int val = Integer.parseInt(str);
                stack.push(val);
            }
        }

        return stack.pop();
    }

    private static boolean isOperation(String str){
        if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")){
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        String[] tokens = {"2","1","+","3","*"};
        System.out.println(evalRPN(tokens));

    }
}
